package com.example.demo.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * oss工具类
 */
@Slf4j
public class OSSUtil {
    // 注意： 外网内网的区别 上线用内网尽量

//    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//    private static String accessKeyId = "LTAI4FnTo8aMBiZb9PJfhSHr";//LTAI4FjLQQhAP9Ph7SFtPnm2  LTAI4FnTo8aMBiZb9PJfhSHr
//    private static String accessKeySecret = "mxlMix8xJdq5YxDBmPNkv7QzkRS7hH";//ZaWKUyEnadU8MKKmMRwexV8iQ1bUm7  mxlMix8xJdq5YxDBmPNkv7QzkRS7hH
//    private static String bucketName = "ph-e-sign"; // cloud-scm-test
    // 云批注的test1
    /*String accessKeyId = "LTAI4FnTo8aMBiZb9PJfhSHr";
    private static String accessKeySecret = "mxlMix8xJdq5YxDBmPNkv7QzkRS7hH";
    private static String bucprivate static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static ketName = "yunpizhu-test1";*/

    // 自己阿里云oss
    /*private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI4FiViAjSRzAr15yQycwU";
    private static String accessKeySecret = "8QDNtrS1E8uX5njfcNQvwwV0vVzEbn";
    private static String bucketName = "file-yby";*/


    //pmo 云mes
//    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//    private static String accessKeyId = "LTAI4FnTo8aMBiZb9PJfhSHr";
//    private static String accessKeySecret = "mxlMix8xJdq5YxDBmPNkv7QzkRS7hH";
//    private static String bucketName = "yunmes-out-test";

    //pmo 云mes
    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI4FjLQQhAP9Ph7SFtPnm2";
    private static String accessKeySecret = "ZaWKUyEnadU8MKKmMRwexV8iQ1bUm7";
    private static String bucketName = "ph-e-sign";


    public static String uploadAliyun(InputStream inputStream, String fileName) throws UnsupportedEncodingException {
        String uploadUrl = "";
        String fileDir = "yby/";
        //fileName = "yby/" + fileName;
        //fileName = new String(fileName.getBytes("UTF-8"),"GBK");
        try {
            // 创建ossclient对象
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                log.info("bucketName不存在");
                return "uploadUrl";
            }
            log.info("获取输入流的大小：" + inputStream.available());
            //log.info("返回的url1: "+url.toString());
            // 创建上传Object的元信息设置Metadata
            ObjectMetadata objectMetadata = getObjectMetadata(inputStream, fileName);
            // 上传文件
            log.info("建立好ossclient对象");
            // 上传文件
            ossClient.putObject(bucketName, fileDir + fileName, inputStream, objectMetadata);
            Date expriration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10); //10年
            URL url = ossClient.generatePresignedUrl(bucketName, fileDir + fileName, expriration);
            uploadUrl = url.toString();
            log.info("返回的url2: " + url.toString());
            ossClient.shutdown();
            log.info("上传成功！");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return uploadUrl;
    }

    public static FileInputStream downLoadAliyun() throws IOException {

        String objectName = "file/" + "123456.pdf";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        File file = new File("/Users/yuanby/yby/temp/" + "12345678-1234.pdf");
        //FileInputStream fileInputStream1 = new FileInputStream(file);
        //System.out.println("fileInputStream1的大小："+fileInputStream1.available());
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, objectName), file);
        FileInputStream fileInputStream2 = new FileInputStream(file);
        System.out.println("fileInputStream2的大小：" + fileInputStream2.available());
        // 关闭OSSClient。
        ossClient.shutdown();
        if (null != file) {
            file.delete();
        }
        return fileInputStream2;
    }

    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = downLoadAliyun();
        System.out.println("流的大小：" + fileInputStream.available());
    }


    /**
     * 获得文件元信息
     *
     * @param fileContent
     * @param fileName
     * @return
     * @throws IOException
     */
    private static ObjectMetadata getObjectMetadata(InputStream fileContent, String fileName) throws IOException {
        log.info("获取文件元信息-----------");
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(fileContent.available());
        objectMetadata.setContentEncoding("utf-8");
        // 设置内容被下载时网页的缓存行为。
        objectMetadata.setCacheControl("no-cache");
        // 指定上传的内容类型。内容类型决定浏览器将以什么形式、什么编码读取文件。如果没有指定则根据文件的扩展名生成，如果没有扩展名则为默认值application/octet-stream。
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        objectMetadata.setContentType(getContentType(fileName));
        return objectMetadata;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static final String getContentType(String fileName) {
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || ".pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || ".docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".apk".equalsIgnoreCase(fileExtension)) {
            return "application/octet-stream";
        }
        if (".zip".equalsIgnoreCase(fileExtension)) {
            return "application/octet-stream";
        }
        if (".pdf".equalsIgnoreCase(fileExtension)) {
            return "application/pdf";
        }
        return "text/html";
    }

}
